package com.wolfheader.wolfgame.service.admin.impl;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.persistence.Query;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.wolfheader.wolfgame.bean.admin.RoleBean;
import com.wolfheader.wolfgame.dao.admin.PermissionDao;
import com.wolfheader.wolfgame.dao.admin.RoleDao;
import com.wolfheader.wolfgame.entity.admin.PermissionEntity;
import com.wolfheader.wolfgame.entity.admin.RoleEntity;
import com.wolfheader.wolfgame.service.admin.RoleService;
import com.wolfheader.wolfgame.service.impl.BaseServiceImpl;
import com.wolfheader.wolfgame.shiro.AdminShiroRealm;

@Service("roleServiceImpl")
public class RoleServiceImpl extends BaseServiceImpl<RoleEntity> implements RoleService {

	@Autowired
	private RoleDao roleDao;

	@Autowired
	private PermissionDao permissionDao;

	@Autowired
	private AdminShiroRealm adminShiroRealm;

	@Override
	public void addRole(RoleBean bean) {
		// TODO Auto-generated method stub
		RoleEntity role = new RoleEntity();
		role.setRolename(bean.getName());
		role.setEnabled(bean.isEnabled());
		role.setRemark(bean.getRemark());
		Set<PermissionEntity> list = new HashSet<PermissionEntity>();
		// role.setPermissionList(permissionList);
		for (int i = 0; i < bean.getPermissions().size(); i++) {
			list.add(permissionDao.findOne(bean.getPermissions().get(i)));
		}
		role.setPermissions(list);
		adminShiroRealm.clearAllCachedAuthorizationInfo();
		roleDao.save(role);
	}

	public void delete(Long id) {
		roleDao.delete(id);
		adminShiroRealm.clearAllCachedAuthorizationInfo();
	}

	@Override
	public boolean modif(Long id, RoleBean bean) {
		RoleEntity role = roleDao.findOne(id);
		if (role == null) {
			return false;
		}
		role.setRolename(bean.getName());
		role.setEnabled(bean.isEnabled());
		role.setRemark(bean.getRemark());
		Set<PermissionEntity> list = new HashSet<PermissionEntity>();
		// role.setPermissionList(permissionList);
		for (int i = 0; i < bean.getPermissions().size(); i++) {
			list.add(permissionDao.findOne(bean.getPermissions().get(i)));
		}
		role.setPermissions(list);
		adminShiroRealm.clearAllCachedAuthorizationInfo();
		roleDao.save(role);
		return true;
	}

	@Override
	public List<RoleEntity> findRolesByAdminId(Long adminId) {
		// String hql = "select r from RoleEntity r where r.gameid=:gameid order
		// by r.totalScore desc,r.recordDateTime asc";
		// Query query = em.createQuery(hql);
		// query.setParameter("gameid", gameid);
		// query.setFirstResult(0);
		// return query.getResultList();
		return null;
	}

}
